package org.lab.data;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.ListIterator;

import sun.util.calendar.CalendarUtils;
import sun.util.resources.CalendarData;

public class DateUtil {
	
	Ticker ticker;
	
	DateUtil(Ticker ticker) {
		this.ticker = ticker;
	}

	public boolean isFirstDayOfMonth(Quote quote) {
		if (ticker.getQuotes().indexOf(quote) != 1) {
			Quote quoteBefore = ticker.getQuotes().get(ticker.getQuotes().indexOf(quote)+1);
			return (quote.getDate().getMonth() > quoteBefore.getDate().getMonth());
		} else {
			return false;
		}
	}
	
	public boolean isLastDayOfMonth(Quote quote) {
		if (ticker.getQuotes().indexOf(quote) != 0) {
			Quote quoteAfter = ticker.getQuotes().get(ticker.getQuotes().indexOf(quote)-1);
			return (quote.getDate().getMonth() < quoteAfter.getDate().getMonth());
		} else {
			return false;
		}
	}

	public Quote nextClosestQuote(Quote quote) {
		if (quote != null) {
			return quote;			
		} else {
			Quote closest = ticker.getQuotes().get(0);
			for(Quote quoteLoop:ticker.getQuotes()) {
				if ((quoteLoop.getDate().after(quote.getDate())) && (quoteLoop.getDate().after(closest.getDate()))){
					closest = quoteLoop;
				}
			}
			return closest;
		}
	}
	
	public Quote latestClosestQuote(Quote quote) {
		if (quote != null) {
			return quote;			
		} else {
			Quote closest = ticker.getQuotes().get(ticker.getQuotes().size());
			for(ListIterator<Quote> it = ticker.getQuotes().listIterator();it.hasPrevious();) {
				Quote quoteLoop = (Quote) it.previous();
				if ((quoteLoop.getDate().after(quote.getDate())) && (quoteLoop.getDate().after(closest.getDate()))){
					closest = quoteLoop;
				}
			}
			return closest;
		}
	}
	
	public int getPosOnTheWeek(Quote quote) {
		if (quote == null) {
			return 0;
		} else {
			GregorianCalendar cal = new GregorianCalendar();
			cal.setTime(quote.getDate());
			cal = (GregorianCalendar) cal.getInstance();
			int day = cal.get(cal.DAY_OF_WEEK);
			System.out.println(cal.getTime());
		}
		return 0;
	}

	public int getPosOnTheMonth(Quote quote) {
		// TODO
		return 0;
	}
	
	public int getPosOnTheWeek(Date date) {
		return this.getPosOnTheWeek(ticker.getQuote(date));
	}

	public int getPosOnTheMonth(Date date) {
		return this.getPosOnTheMonth(ticker.getQuote(date));
	}

	public boolean isDefined(Date date) {
		if (ticker.getQuote(date) == null) return false;
		else return true;
	}
	
	public boolean isWeekend(Date date) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		if ((cal.get(cal.DAY_OF_WEEK) == 0) || (cal.get(cal.DAY_OF_WEEK) == 6)) {
			return true;
		} else {return false;}
	}
	
	public Quote nextClosestQuote(Date date) {
		return this.nextClosestQuote(ticker.getQuote(date));
	}
	
	public Quote latestClosestQuote(Date date) {
		return this.latestClosestQuote(ticker.getQuote(date));
	}


}
